// let url = "http://video.midefangzhi.com"
// let url = "http://47.93.176.208:3003"
let url = 'https://jocy.6b7.xyz';
import MD5 from "@/md5";
import commonUtil from "@/store/commonUtil.js";

// 生成签名的函数
function generateSignature() {
    const jocy = 'jocy';
    const timestamp = Math.floor(Date.now() / 1000).toString();
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const randomStr = Array.from({
        length: 10
    }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
    const reversedRandomStr = randomStr.split('').reverse().join('');

    // 拼接字符串
    const signData = `${jocy}&${timestamp}&${randomStr}`;
    const md5Hash = MD5.hex_md5(signData).toString();

    // 最终签名
    const signature = `${md5Hash}.${reversedRandomStr}`;
    // 获取token
    const token = commonUtil.getItem("token") || '';
    return {
        s: signature,
        t: timestamp,
        'x-token': token
    };
}


export const post = (opt) => {
    let data = opt.data || {};
    let cmd = opt.cmd || "";
    // console.log(data, "《=====》")
    return new Promise((resolve, reject) => {
        uni.request({
            url: url + cmd, //仅为示例，并非真实接口地址。
            data: data,
            method: "post",
            header: generateSignature(),
            success: (res) => {
                resolve(res.data)
                if (res.data.code != 20000) {
                    uni.showToast({
                        title: res.data.message || "服务器开小差了！",
                        duration: 2000
                    });
                }
            },
            fail: (res) => {
                console.log("error", res)
                reject(res)
                uni.showToast({
                    title: res.message || "服务器开小差了！",
                    duration: 2000
                });
            }
        });
    })
}

export const get = (opt) => {
    let cmd = opt.cmd || "";
    let data = opt.data || {}
    // console.log(data, "《=====》")
    const header = {
        ...generateSignature(),
        "content-type": "application/json"
        // "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
    }

    console.log(data, "《=====》", header)

    return new Promise((resolve, reject) => {
        uni.request({
            url: url + cmd, //仅为示例，并非真实接口地址。
            method: "GET",
            data: data,
            header: header,
            success: (res) => {
                console.log(cmd, "《=====》", res)
                resolve(res.data)
            },
            fail: (error) => {
                console.log("error", error)
                uni.showToast({
                    title: res.message || "服务器开小差了！",
                    duration: 2000
                });
                reject(res)
            }
        });
    })
}